package com.tencreat.mall.controller.app;

import com.google.common.collect.Lists;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.controller.BaseController;
import com.tencreat.common.core.domain.model.LoginUser;
import com.tencreat.common.enums.OrderType;
import com.tencreat.common.enums.UserType;
import com.tencreat.common.enums.mall.AllEnum;
import com.tencreat.common.utils.SecurityUtils;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.mall.MallCoupon;
import com.tencreat.domain.mall.MallCouponUser;
import com.tencreat.domain.mall.MallZoneGoods;
import com.tencreat.domain.mall.dto.CouponRequDTO;
import com.tencreat.domain.mall.dto.OrderMallBudgetDTO;
import com.tencreat.domain.mall.dto.StoreOrderMallBudgetDTO;
import com.tencreat.domain.mall.vo.*;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.mall.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags={"8-优惠券"})
@RestController
@RequestMapping("/api/coupon")
public class MallCouponController extends BaseController {
    @Autowired
    private IMallCouponService mallCouponService;//优惠券信息及规则
    @Autowired
    private IMallCouponUserService mallCouponUserService;//优惠券用户使用
    //@Autowired
    //private IMallZoneGoodsService zoneGoodsService;//专区商品
    @Autowired
    private IMallOrderService mallOrderService;//订单
    @Autowired
    private IMallUserService mallUserService;//用户

    @Autowired
    private IMallStoreOrderService mallStoreOrderService;//店铺订单

    @ApiOperation(value = "根据商城订单查询优惠券")
    @PostMapping("/getOrderCoupon")
    public HttpResult<List<MallCouponUser>> getOrderCoupon(@RequestBody OrderMallBudgetDTO orderMallBudgetPo) {
        // 查询用户自己 未使用的优惠券
        // 可用集合
        List<MallCouponUser> usableList = new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (orderMallBudgetPo.getOrderType().compareTo(OrderType.SHOP) != 0){
            return HttpResult.ok();
        }
        // 优惠券列表
        List<MallCouponUser> mallCouponUsers = mallCouponUserService.getUserAllCoupon(loginUser.getAccountLogin().getUuid(), AllEnum.couponType.EXISTENCE.getType());
        if (mallCouponUsers == null || mallCouponUsers.size() <= 0) {
            return HttpResult.ok(usableList);
        }

        // 组装商品信息
        HttpResult<ResOrderMallBudgetVO> budget = mallOrderService.budget(orderMallBudgetPo, loginUser);
        if (budget != null && budget.getCode() == 200) {
            if (budget.getData() != null) {
                List<ResOrderMallBudgetGoodsVO> goods = budget.getData().getGoods();
                // 查询商品专区
                //List<MallZoneGoods> list = zoneGoodsService.lambdaQuery().in(MallZoneGoods::getGoodsId, Lists.transform(goods, g -> g.getGoodsId())).list();
                //List<Long> zoneIds = null;
      /*          if (list != null && list.size() >0){
                    zoneIds = Lists.transform(list,l->l.getZoneId());
                }*/
                // 不可用
                List<MallCouponUser> notUsableList = new ArrayList<>();
                // 过滤出指定商品
                LocalDateTime date = LocalDateTime.now();
                // 查询专区商品
                for (MallCouponUser couponUser : mallCouponUsers) {
                    // 商品限制类型: 0全商品, 1商品。
                    boolean range = false;
                    boolean price = false;
                    // 判断使用时间
                    if (couponUser.getStartTime().isAfter(date)) {
                        couponUser.setRemark("未到时间");
                        notUsableList.add(couponUser);
                        continue;
                    } else if (couponUser.getEndTime().isBefore(date)) {
                        couponUser.setRemark("过期");
                        notUsableList.add(couponUser);
                        continue;
                    }
                    for (ResOrderMallBudgetGoodsVO goods1 : goods) {
                        if (goods1.getGoodsNum() == null){
                            goods1.setGoodsNum(1);
                        }
                        if (couponUser.getGoodsType() == 0) {//全商品
                            range = true;
                            // 判断价格符不符合
                            if (range && couponUser.getMin().doubleValue() <= budget.getData().getPricePay().doubleValue()) {
                                price = true;
                            }
                        }
                        /*else if (couponUser.getGoodsType() == 1 && zoneIds != null && zoneIds.size() >0){
                            String[] split = couponUser.getGoodsValue().split(",");
                            List<String> goodsValues = Arrays.asList(split);
                            range = Collections.disjoint(zoneIds, goodsValues);
                            BigDecimal multiply = BigDecimal.valueOf(goods1.getGoodsPrice()).multiply(BigDecimal.valueOf(goods1.getGoodsNum()));
                            // 判断价格符不符合
                            if (range && couponUser.getMin().doubleValue() <= multiply.doubleValue()) {
                                price = true;
                            }
                        }*/
                        else if (couponUser.getGoodsType() == 1 && couponUser.getGoodsValue().contains(goods1.getGoodsId() + "")) {
                            range = true;
                            BigDecimal multiply = BigDecimal.valueOf(goods1.getGoodsPrice()).multiply(BigDecimal.valueOf(goods1.getGoodsNum()));
                            // 判断价格符不符合
                            if (range && couponUser.getMin().doubleValue() <= multiply.doubleValue()) {
                                price = true;
                            }
                        }
                    }
                    if (!range || !price) {
                        couponUser.setRemark("不适用");
                        notUsableList.add(couponUser);
                    } else {
                        usableList.add(couponUser);
                    }
                }
            }
        }

        return HttpResult.ok(usableList);
    }

    @ApiOperation(value="查询所有优惠券")
    @PostMapping("/listAll")
    public HttpResult<List<MallCoupon>> listAll() {
        // 查询用户信息
        MallUser user = mallUserService.lambdaQuery().eq(MallUser::getUuid,getLoginCheck().getAccountLogin().getUuid()).one();
        List<Long> types = new ArrayList<>();
        types.add(0L);
        types.add(2L);
/*        if (user.getUserLevel() == UserType.INTERMEDIATE_MEMBER){
            types.add(1L);
        }*/
        // 查询优惠券信息
        List<MallCoupon> list = mallCouponService.lambdaQuery()
                .eq(MallCoupon::getStatus,0)
                .in(MallCoupon::getType,types)
                .eq(MallCoupon::getProvideStatus,0)
                .ge(MallCoupon::getEndTime,LocalDateTime.now())
                .list();
        if (list != null && list.size() >0){
            // 查询已领取的优惠券
            List<MallCouponUser> list1 = mallCouponUserService.lambdaQuery().eq(MallCouponUser::getUuid, getLoginCheck().getAccountLogin().getUuid()).list();
            if (list1 != null){
                Map<Long,List<MallCouponUser>> map = list1.stream().collect(Collectors.groupingBy(MallCouponUser::getCouponId));
                for (MallCoupon c:list) {
                    if (map !=null && map.get(c.getId()) != null){
                        c.setCouponStatus(1);
                    }else if (c.getSurplus() <=0){
                        c.setCouponStatus(2);
                    }else {
                        c.setCouponStatus(0);
                    }
                    // 计算百分比
                    if (c.getTotal() == 0){
                        c.setReceived(100);
                        continue;
                    }
                    BigDecimal divide = BigDecimal.valueOf(c.getSurplus()).divide(BigDecimal.valueOf(c.getTotal()), 2, BigDecimal.ROUND_HALF_DOWN);
                    if (divide.doubleValue() >= 1){
                        c.setReceived(0);
                    }else if (divide.doubleValue() <= 0){
                        c.setReceived(100);
                    }else {
                        BigDecimal multiply = BigDecimal.valueOf(1).subtract(divide).multiply(BigDecimal.valueOf(100));
                        c.setReceived(multiply.intValue());
                    }
                }
            }
        }

        return HttpResult.ok(list);
    }

    @ApiOperation(value="查询我的优惠券V2")
    @PostMapping("/listMySelf")
    public HttpResult<List<MallCoupon>> listMySelf(@RequestBody MallCoupon mallCoupon) {
        // 查询已领取的优惠券
        List<MallCoupon> list = mallCouponUserService.getCouponByUuidV2(getLoginCheck().getAccountLogin().getUuid(),mallCoupon.getUsedStatus());

        return HttpResult.ok(list);
    }

    @ApiOperation(value="领取优惠券")
    @PostMapping("/receiveCoupon")
    public HttpResult<String> receiveCoupon(@RequestBody MallCouponUser mallCoupon) {
        Long uuid = getLoginCheck().getAccountLogin().getUuid();
        // 查询优惠券信息
        MallCoupon one = mallCouponService.lambdaQuery().eq(MallCoupon::getId, mallCoupon.getCouponId()).one();
        if (one !=null){
            if (one.getStatus() !=0){
                return HttpResult.error("该优惠券不可用");
            }
            if (one.getProvideStatus() !=0){
                return HttpResult.error("该优惠券已下架");
            }
            if (one.getEndTime().isBefore(LocalDateTime.now())){
                return HttpResult.error("该优惠券已过期");
            }
            if (one.getSurplus() <=0){
                return HttpResult.error("该优惠券已被领完");
            }
            // 查询已领取的优惠券
            List<MallCouponUser> list = mallCouponUserService.lambdaQuery().eq(MallCouponUser::getUuid, uuid).eq(MallCouponUser::getCouponId,mallCoupon.getCouponId()).list();
            if (list.size() >=one.getLimit()){
                return HttpResult.error("您已领取过该优惠券");
            }
            mallCoupon.setStatus(0);
            mallCoupon.setStartTime(one.getStartTime());
            mallCoupon.setEndTime(one.getEndTime());
            mallCoupon.setUuid(uuid);
            mallCouponUserService.insertMallCouponUser(mallCoupon);
            // 剩余数-1
            mallCouponService.lambdaUpdate().eq(MallCoupon::getId,one.getId()).set(MallCoupon::getSurplus,one.getSurplus() -1).update();

            return HttpResult.ok();
        }


        return HttpResult.error("优惠券信息有误");
    }
}
